package com.waimai.controllor;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.waimai.adapter.RestaurantAdapter;
import com.waimai.constant.DateConstant;
import com.waimai.controllor.ele.EleHttpControllor;
import com.waimai.controllor.meituan.MeituanHttpControllor;
import com.waimai.entity.Address;
import com.waimai.log.Log;
import com.waimai.utils.DateUtils;

public class TimerControllor extends BaseControllor {
	private static TimerControllor controllor;

	public static TimerControllor getInstance() {
		if (controllor == null) {
			controllor = new TimerControllor();
		}
		return controllor;
	}

	/**
	 * 
	 * 
	 */
	public void scheduleExec() {
		Timer day = new Timer();
		day.schedule(new TimerTask() {
			@Override
			public void run() {

				new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						int hour = DateUtils.getHours();
						int minute = DateUtils.getMinutes();
						int intervalMinutes = 1;

						// int intervalMinutes = 999;
						// if (hour >= 0 && hour < 8) {
						//
						// } else if (hour == 8 || (hour == 9 && minute < 30)) {
						// intervalMinutes = 15;
						// } else if (hour < 14) {
						// intervalMinutes = 2;
						// } else if (hour < 16) {
						// intervalMinutes = 15;
						// } else if (hour < 20) {
						// intervalMinutes = 2;
						// } else if (hour < 21) {
						// intervalMinutes = 10;
						// } else if (hour < 22) {
						// intervalMinutes = 5;
						// } else if (hour < 24) {
						// intervalMinutes = 15;
						// }
						if (minute % intervalMinutes == 0) {
							before();
							DBControllor controllor = DBControllor
									.getInstance();
							// // 清空b
							// controllor.clearUnuseTables();
							// 存储,b获取信息并添加信息
							Address[] addresses = controllor.getAddresses();
							if (addresses != null && addresses.length != 0) {
								Map<String, RestaurantAdapter> restaurantMap = new HashMap<String, RestaurantAdapter>();
								restaurantMap.putAll(MeituanHttpControllor
										.getInstance()
										.getRestaurants(addresses));
								restaurantMap.putAll(EleHttpControllor
										.getInstance()
										.getRestaurants(addresses));
								controllor.updateRestaurants(restaurantMap);
							} else {
								Log.e("address is null :" + (addresses == null)
										+ " or addressLength is 0 ");
							}
							// // 替换使用中的表
							// controllor.changeTablesStatus();
							// // 替换info，必须在替换表之后调用
							// FileControllor.getInstance().changeInfo(
							// controllor.getTableStatus());
							after("timer once over " + hour + ":" + minute
									+ "  ");
						}
					}
				}).start();
			}
		}, 0, DateConstant.MINUTE);
	}
}
